﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using System.Security;
using System.Security.Permissions;

using System.Runtime.InteropServices;
using System.IO;

namespace ConvertDotNetLIBHelper
{
    [SecurityCritical]
    public static class Helper
    {    
        // In future each installed Source adapter will expose the file 'format' it can handle and how to identify it from the first 1024 bytes.
        // however for now, for testing purposes, lets leave the values here.
        //
        // I found http://www.wotsit.org and Gary Kessler's File Signature page http://www.garykessler.net/library/file_sigs.html to be really useful.
        //
        private static readonly Int32 _formatIcon = BitConverter.ToInt32(new Byte[4] { 0x00, 0x00, 0x01, 0x00 }, 0);
        private static readonly Int64 _formatPng = BitConverter.ToInt64(new Byte[8] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, 0);
        private static readonly Int64 _formatMSOffice = BitConverter.ToInt64(new Byte[8] { 0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1 }, 0);
        private static readonly Int32 _formatMicrosoftWordDocument = BitConverter.ToInt32(new Byte[4] { 0xEC, 0xA5, 0xC1, 0x00 }, 0);
        
        public static string GetFileType(string filenameAndPath)
        {
            // open the file and read the first 1024 bytes to identify format...
            BinaryReader fileReader = new BinaryReader(File.Open(filenameAndPath, FileMode.Open, FileAccess.Read, FileShare.Read));

            // get the 1024 bytes
            byte[] fileContents = new byte[1024];
            fileReader.Read(fileContents, 0, 1024);
            
            // identify file format:

            // '32-bit' checks
            if (BitConverter.ToInt32(fileContents, 0) == _formatIcon)
                return "Icon";

            // '64-bit' checks
            if (BitConverter.ToInt64(fileContents, 0) == _formatPng)
                return "Png";

            if (BitConverter.ToInt64(fileContents, 0) == _formatMSOffice)
            {
                if (BitConverter.ToInt32(fileContents, 512) == _formatMicrosoftWordDocument)
                    return "Microsoft Word Document";
            }

            return "Unknown";
        }
    }
}
